package com.wmd.core.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * @Author: hy
 * @Description:
 * @Date: 2021/4/12
 */

public class MapToBeanUtils {

    /**
     * map转bean
     * @param map
     * @return
     */
    public static  <T> T mapToBean(Map<String, Object> map, Class<T> beanClass){

        T object = null;
        try {
            object = beanClass.newInstance();
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields){
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                    continue;
                }
                field.setAccessible(true);
                if (map.containsKey(field.getName())) {
                    //判断是否是Integer型
                    if(field.getGenericType().getTypeName().contains("Integer")) {
                        field.set(object, Integer.parseInt(map.get(field.getName()).toString()));
                    }else if (field.getType().getTypeName().contains("String")){
                        field.set(object, String.valueOf(map.get(field.getName())));
                    }
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return object;
    }
}
